#!/usr/bin/env bash
# -*- tab-width : 4; indent-tabs-mode : nil -*-
#
#    Copyright (C) 2014 Norbert Thiebaud
#    License: GPLv3
#

# run debug=1 setup ... to debug
if [ -n "$debug" ] ; then
    set -x
fi

# get the abolute path to the directory containing the main script
BASE_DIR=$(dirname "$0")
pushd ${BASE_DIR} > /dev/null
BASE_DIR=$(pwd)
popd > /dev/null

source "$BASE_DIR/bin/utils.sh"

do_help()
{
cat <<EOF
setup [ --help ] [ -v ] [ --prereq ] [ --jenkins ] [ --jenkins-san ] [ --dev ] [ --new <name> ] [ --refresh ] [ --force ]

setup the necessary environment to build.
run --prereq first to determine if your os version is currently supported by the tool
it will also tell you the list of thing, if any that need to be done prior to running the setup

--jenkins prepare what is needed for a jenkins slave operation
--jenkins-san prepare extra stuff needed for Jenkins' "UBSAN Linux Build" job
--dev setup a dev build environment in dev/core
--new <name> create a clone of core in dev/<name>
--refresh update the mirror repo and git gc the repos under dev
--force reinstall the dependant packages.
--git-hooks for lode dev only: install the necessary git-hooks to be able to push a commit to lode via gerrit
EOF
}


#
# Main
#

V=0
DO_PREREQ=0
DO_JENKINS=0
DO_JENKINS_SAN=0
DO_DEV=0
DO_NEW=0
DO_REFRESH=0
DO_FORCE=0

while [ "${1}" != "" ]; do
    parm=${1%%=*}
    arg=${1#*=}
    has_arg=
    if [ "${1}" != "${parm?}" ] ; then
        has_arg=1
    else
        arg=""
    fi

    case "${parm}" in
        --dev)
            DO_DEV=1
            ;;
        -n|--new)
            DO_NEW=1
            ;;
        --refresh)
            DO_REFRESH=1
            ;;
        --force)
            DO_FORCE=1
            ;;
        --git-hooks)
            setup_git_hooks
            exit
            ;;
        -h|--help)  # display help
            do_help
            exit
            ;;
        -p|--prereq)
            DO_PREREQ=1
            ;;
        --jenkins)
            DO_JENKINS=1
            ;;
        --jenkins-san)
            DO_JENKINS_SAN=1
            ;;
        -v)  # print more messages
            V=1
            ;;
        -*)
            die "Invalid option $1"
            ;;
        *)
            if [ "$DO_NEW" = 1 ] ; then
                REPO="$1"
            else
                die "Invalid argument $1"
            fi
            ;;
    esac
    shift
done

determine_os  # this will overload the usefull bits based on the machine we run on

if [ "$DO_PREREQ" = "1" ] ; then
    display_prereq
    exit 0;
fi

if [ "$DO_NEW" = 1 ] ; then
    create_new_work_clone "$REPO"
    exit 0;
fi

if [ "$DO_REFRESH" = 1 ] ; then
    refresh_repos
    exit 0
fi

setup_base_tree

setup_adm_repos

install_build_dep

if [ "$DO_JENKINS" = "1" ] ; then
    setup_jenkins_slave
fi

if [ "$DO_DEV" = "1" ] ; then
    setup_dev
fi

final_notes
